<template>
  <div class="admin-course-management">
    <h2>课程管理（管理员）</h2>
    
    <!-- 课程列表 -->
    <div class="course-list-section">
      <div class="header-actions">
        <h3>所有课程</h3>
        <el-button type="primary" @click="openCourseDialog(null)">添加课程</el-button>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="filter-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称"
          style="width: 200px; margin-right: 10px"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="semesterFilter" placeholder="学期筛选" clearable @change="handleSearch" style="margin-right: 10px">
          <el-option label="2024春季" value="2024春季" />
          <el-option label="2024秋季" value="2024秋季" />
          <el-option label="2025春季" value="2025春季" />
          <el-option label="2025秋季" value="2025秋季" />
        </el-select>
        <el-select v-model="departmentFilter" placeholder="院系筛选" clearable @change="handleDepartmentChange" style="margin-right: 10px">
          <el-option 
            v-for="dept in departments" 
            :key="dept.id" 
            :label="dept.name" 
            :value="dept.id" 
          />
        </el-select>
        <el-select v-model="majorFilter" placeholder="专业筛选" clearable @change="handleSearch" :disabled="!departmentFilter">
          <el-option 
            v-for="major in majors" 
            :key="major.id" 
            :label="major.name" 
            :value="major.id" 
          />
        </el-select>
      </div>
      
      <el-table :data="filteredCourses" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="description" label="课程简介" />
        <el-table-column prop="credits" label="学分" width="80" />
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="semester" label="学期" width="120" />
        <el-table-column label="授课教师" width="120">
          <template #default="scope">
            {{ scope.row.teacherName || scope.row.teacherId }}
          </template>
        </el-table-column>
        <el-table-column prop="schedule" label="上课时间" width="150" />
        <el-table-column prop="location" label="上课地点" width="150" />
        <el-table-column label="课程容量" width="150">
          <template #default="scope">
            <el-progress 
              :percentage="Math.round((scope.row.currentStudents / scope.row.capacity) * 100)" 
              :format="() => `${scope.row.currentStudents}/${scope.row.capacity}`"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="openCourseDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="viewStudents(scope.row)"
            >
              查看学生
            </el-button>
            <el-popconfirm
              title="确定要删除这门课程吗？"
              @confirm="deleteCourse(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 课程编辑对话框 -->
    <el-dialog
      :title="isEditMode ? '编辑课程' : '添加课程'"
      v-model="courseDialogVisible"
      width="800px"
    >
      <el-form :model="currentCourse" label-width="120px" :rules="courseRules" ref="courseForm">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="currentCourse.name" />
        </el-form-item>
        
        <el-form-item label="课程简介" prop="description">
          <el-input v-model="currentCourse.description" type="textarea" :rows="3" />
        </el-form-item>
        
        <el-form-item label="所属院系" prop="departmentId">
          <el-select v-model="currentCourse.departmentId" placeholder="请选择院系" @change="handleCourseDepChange">
            <el-option 
              v-for="dept in departments" 
              :key="dept.id" 
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属专业" prop="majorId">
          <el-select v-model="currentCourse.majorId" placeholder="请选择专业" :disabled="!currentCourse.departmentId">
            <el-option 
              v-for="major in courseMajors" 
              :key="major.id" 
              :label="major.name" 
              :value="major.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程类型" prop="type">
          <el-select v-model="currentCourse.type" placeholder="请选择课程类型">
            <el-option label="选修课程" value="选修课程" />
            <el-option label="必修课程" value="必修课程" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学分" prop="credits">
          <el-input-number v-model="currentCourse.credits" :min="1" :max="10" />
        </el-form-item>
        
        <el-form-item label="平时成绩占比" prop="regularGradeRatio">
          <el-input-number 
            v-model="currentCourse.regularGradeRatio" 
            :min="0" 
            :max="1" 
            :step="0.1" 
            :precision="2"
          />
        </el-form-item>
        
        <el-form-item label="期末成绩占比" prop="examGradeRatio">
          <el-input-number 
            v-model="currentCourse.examGradeRatio" 
            :min="0" 
            :max="1" 
            :step="0.1" 
            :precision="2"
          />
        </el-form-item>
        
        <el-form-item label="课程容量" prop="capacity">
          <el-input-number v-model="currentCourse.capacity" :min="1" :max="200" />
          <span v-if="currentCourse.type === '必修课程'" style="color:#909399;font-size:12px;">必修课程容量自动同步已选人数，最大容量由教师设置</span>
        </el-form-item>
        
        <el-form-item label="教师ID" prop="teacherId">
          <el-input v-model="currentCourse.teacherId" />
        </el-form-item>
        
        <el-form-item label="学期" prop="semester">
          <el-select v-model="currentCourse.semester" placeholder="请选择学期">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="currentCourse.location" placeholder="如：教学楼A101" />
        </el-form-item>
        
        <el-form-item label="上课时间" prop="schedule">
          <div class="schedule-table">
            <table>
              <thead>
                <tr>
                  <th>时间段</th>
                  <th>星期一</th>
                  <th>星期二</th>
                  <th>星期三</th>
                  <th>星期四</th>
                  <th>星期五</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(time, timeIndex) in timeSlots" :key="timeIndex">
                  <td>{{ time }}</td>
                  <td v-for="day in 5" :key="day">
                    <el-checkbox 
                      v-model="scheduleMatrix[timeIndex][day-1]"
                      @change="updateScheduleString"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="schedule-preview">
            当前选择: {{ currentCourse.schedule || '未选择' }}
          </div>
        </el-form-item>
        
        <el-form-item label="总课时" prop="totalHours">
          <el-input-number 
            v-model="currentCourse.totalHours" 
            :min="1" 
            :disabled="true"
            :controls="false"
          />
          <span class="description">（根据所选上课时间自动计算，每个时间段为2课时）</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="courseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCourse" :loading="saving">
            {{ isEditMode ? '保存修改' : '添加课程' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 学生列表对话框 -->
    <el-dialog
      title="课程学生列表"
      v-model="studentsDialogVisible"
      width="900px"
    >
      <div v-if="selectedCourse" class="course-info-header">
        <h3>{{ selectedCourse.name }}</h3>
        <p>学期: {{ selectedCourse.semester }} | 学分: {{ selectedCourse.credits }} | 教师: {{ selectedCourse.teacherName || selectedCourse.teacherId }}</p>
      </div>
      
      <el-table :data="courseStudents" style="width: 100%" v-loading="studentsLoading">
        <el-table-column prop="studentNumber" label="学号" width="120" />
        <el-table-column prop="studentName" label="姓名" width="120" />
        <el-table-column prop="major" label="专业" width="150" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="regularGrade" label="平时成绩" width="100">
          <template #default="scope">
            {{ scope.row.regularGrade !== null ? scope.row.regularGrade : '未录入' }}
          </template>
        </el-table-column>
        <el-table-column prop="examGrade" label="期末成绩" width="100">
          <template #default="scope">
            {{ scope.row.examGrade !== null ? scope.row.examGrade : '未录入' }}
          </template>
        </el-table-column>
        <el-table-column prop="finalGrade" label="最终成绩" width="100">
          <template #default="scope">
            <span :class="{ 'failed-grade': scope.row.finalGrade !== null && scope.row.finalGrade < 60 }">
              {{ scope.row.finalGrade !== null ? scope.row.finalGrade : '未录入' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.finalGrade !== null" :type="scope.row.passed ? 'success' : 'danger'">
              {{ scope.row.passed ? '通过' : '未通过' }}
            </el-tag>
            <el-tag v-else type="info">未评分</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'AdminCourseManagement',
  setup() {
    const courses = ref([])
    const loading = ref(false)
    const saving = ref(false)
    const courseDialogVisible = ref(false)
    const studentsDialogVisible = ref(false)
    const courseForm = ref(null)
    const isEditMode = ref(false)
    const searchQuery = ref('')
    const semesterFilter = ref('')
    const departmentFilter = ref(null)
    const majorFilter = ref(null)
    const selectedCourse = ref(null)
    const courseStudents = ref([])
    const studentsLoading = ref(false)
    const departments = ref([])
    const majors = ref([])
    const courseMajors = ref([])
    
    // 时间段定义
    const timeSlots = [
      '8:00-9:40',
      '10:00-11:40',
      '14:00-15:40',
      '16:00-17:40',
      '19:00-20:40'
    ]
    
    // 课程表矩阵 [时间段][星期几]
    const scheduleMatrix = reactive(Array(5).fill().map(() => Array(5).fill(false)))
    
    // 当前编辑的课程
    const currentCourse = reactive({
      id: '',
      name: '',
      description: '',
      departmentId: null,
      majorId: null,
      credits: 3,
      regularGradeRatio: 0.40,
      examGradeRatio: 0.60,
      capacity: 40,
      currentStudents: 0,
      semester: '2024春季',
      teacherId: '',
      schedule: '',
      location: '',
      totalHours: 0,
      type: '选修课程'
    })
    
    // 表单验证规则
    const courseRules = {
      name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
      description: [{ required: true, message: '请输入课程简介', trigger: 'blur' }],
      departmentId: [{ required: true, message: '请选择院系', trigger: 'change' }],
      majorId: [{ required: true, message: '请选择专业', trigger: 'change' }],
      credits: [{ required: true, message: '请输入学分', trigger: 'blur' }],
      capacity: [{ required: true, message: '请输入课程容量', trigger: 'blur' }],
      teacherId: [{ required: true, message: '请输入教师ID', trigger: 'blur' }],
      semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
      schedule: [{ required: true, message: '请选择上课时间', trigger: 'change' }],
      location: [{ required: true, message: '请输入上课地点', trigger: 'blur' }],
      type: [{ required: true, message: '请选择课程类型', trigger: 'change' }]
    }
    
    // 过滤课程列表
    const filteredCourses = computed(() => {
      let result = [...courses.value]
      
      if (searchQuery.value) {
        result = result.filter(course => 
          course.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          course.description.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      if (semesterFilter.value) {
        result = result.filter(course => course.semester === semesterFilter.value)
      }
      
      if (departmentFilter.value) {
        result = result.filter(course => course.departmentId === departmentFilter.value)
      }
      
      if (majorFilter.value) {
        result = result.filter(course => course.majorId === majorFilter.value)
      }
      
      return result
    })
    
    // 获取所有课程
    const fetchCourses = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/admin/courses')
        courses.value = response.data || []
        console.log('获取到课程数量:', courses.value.length)
      } catch (error) {
        console.error('获取课程失败:', error)
        ElMessage.error('获取课程失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取所有院系
    const fetchDepartments = async () => {
      try {
        const response = await axios.get('/api/departments')
        departments.value = response.data || []
        console.log('获取到院系数量:', departments.value.length)
      } catch (error) {
        console.error('获取院系失败:', error)
        ElMessage.error('获取院系失败')
      }
    }
    
    // 根据院系ID获取专业
    const fetchMajorsByDepartment = async (departmentId) => {
      if (!departmentId) {
        majors.value = []
        return
      }
      
      try {
        const response = await axios.get(`/api/departments/${departmentId}/majors`)
        majors.value = response.data || []
        console.log('获取到专业数量:', majors.value.length)
      } catch (error) {
        console.error('获取专业失败:', error)
        ElMessage.error('获取专业失败')
      }
    }
    
    // 处理院系变更（筛选）
    const handleDepartmentChange = (departmentId) => {
      majorFilter.value = null
      fetchMajorsByDepartment(departmentId)
      handleSearch()
    }
    
    // 处理院系变更（课程编辑）
    const handleCourseDepChange = (departmentId) => {
      currentCourse.majorId = null
      fetchMajorsByDepartmentForCourse(departmentId)
    }
    
    // 根据院系ID获取专业（课程编辑用）
    const fetchMajorsByDepartmentForCourse = async (departmentId) => {
      if (!departmentId) {
        courseMajors.value = []
        return
      }
      
      try {
        const response = await axios.get(`/api/departments/${departmentId}/majors`)
        courseMajors.value = response.data || []
      } catch (error) {
        console.error('获取专业失败:', error)
        ElMessage.error('获取专业失败')
      }
    }
    
    // 更新课程表字符串
    const updateScheduleString = () => {
      let scheduleStr = ''
      let selectedCount = 0
      
      for (let day = 0; day < 5; day++) {
        for (let time = 0; time < 5; time++) {
          if (scheduleMatrix[time][day]) {
            const dayText = ['一', '二', '三', '四', '五'][day]
            scheduleStr += `星期${dayText}${timeSlots[time]}`
            selectedCount++
          }
        }
      }
      
      currentCourse.schedule = scheduleStr
      // 计算总课时 (16周 × 选中的时间段数 × 2课时/时间段)
      currentCourse.totalHours = 16 * selectedCount * 2
    }
    
    // 从课程表字符串解析到矩阵
    const parseScheduleToMatrix = (scheduleStr) => {
      // 重置矩阵
      for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; j++) {
          scheduleMatrix[i][j] = false
        }
      }
      
      if (!scheduleStr) return
      
      const dayMap = { '一': 0, '二': 1, '三': 2, '四': 3, '五': 4 }
      
      // 分割多个时间段
      const segments = scheduleStr.split('星期').filter(s => s.trim())
      
      segments.forEach(segment => {
        const dayChar = segment.charAt(0)
        const timeRange = segment.substring(1).trim()
        
        const day = dayMap[dayChar]
        if (day === undefined) return
        
        const timeIndex = timeSlots.findIndex(t => t === timeRange)
        if (timeIndex !== -1) {
          scheduleMatrix[timeIndex][day] = true
        }
      })
    }
    
    // 处理搜索
    const handleSearch = () => {
      console.log('搜索条件更新，关键词:', searchQuery.value, '学期:', semesterFilter.value)
    }
    
    // 打开课程编辑对话框
    const openCourseDialog = (course) => {
      isEditMode.value = !!course
      
      // 重置课程表矩阵
      for (let i = 0; i < 5; i++) {
        for (let j = 0; j < 5; j++) {
          scheduleMatrix[i][j] = false
        }
      }
      
      if (course) {
        // 编辑模式，复制课程数据
        Object.keys(currentCourse).forEach(key => {
          if (key in course) {
            currentCourse[key] = course[key]
          }
        })
        
        // 解析课程表字符串到矩阵
        parseScheduleToMatrix(course.schedule)
        
        // 如果有院系ID，获取对应的专业列表
        if (course.departmentId) {
          fetchMajorsByDepartmentForCourse(course.departmentId)
        }
      } else {
        // 新建模式，重置表单
        Object.keys(currentCourse).forEach(key => {
          if (key === 'credits') currentCourse[key] = 3
          else if (key === 'capacity') currentCourse[key] = 40
          else if (key === 'semester') currentCourse[key] = '2024春季'
          else if (key === 'regularGradeRatio') currentCourse[key] = 0.40
          else if (key === 'examGradeRatio') currentCourse[key] = 0.60
          else if (key === 'totalHours') currentCourse[key] = 0
          else if (key === 'type') currentCourse[key] = '选修课程'
          else if (key === 'departmentId' || key === 'majorId') currentCourse[key] = null
          else if (key === 'currentStudents') currentCourse[key] = 0
          else currentCourse[key] = ''
        })
      }
      
      courseDialogVisible.value = true
    }
    
    // 保存课程
    const saveCourse = async () => {
      if (!courseForm.value) return
      
      await courseForm.value.validate(async (valid) => {
        if (!valid) return
        
        saving.value = true
        try {
          // 不再对必修课程的 capacity 做任何处理，始终传递教师输入的值
          let response
          if (isEditMode.value) {
            // 编辑现有课程
            const courseId = String(currentCourse.id);
            response = await axios.put(`/api/admin/courses/${courseId}`, currentCourse)
          } else {
            // 新建课程
            response = await axios.post('/api/admin/courses', currentCourse)
          }
          if (response.data) {
            ElMessage.success(isEditMode.value ? '课程更新成功' : '课程添加成功')
            courseDialogVisible.value = false
            fetchCourses()
          } else {
            ElMessage.error(isEditMode.value ? '课程更新失败' : '课程添加失败')
          }
        } catch (error) {
          ElMessage.error('保存课程失败')
        } finally {
          saving.value = false
        }
      })
    }
    
    // 删除课程
    const deleteCourse = async (courseId) => {
      try {
        const courseIdStr = String(courseId);
        console.log('删除课程，courseId:', courseIdStr);
        
        const response = await axios.delete(`/api/admin/courses/${courseIdStr}`)
        if (response.data) {
          ElMessage.success('课程删除成功')
          fetchCourses()
        } else {
          ElMessage.error('课程删除失败')
        }
      } catch (error) {
        console.error('删除课程失败:', error)
        ElMessage.error('删除课程失败')
      }
    }
    
    // 查看课程学生
    const viewStudents = async (course) => {
      selectedCourse.value = course
      studentsDialogVisible.value = true
      studentsLoading.value = true
      
      try {
        const courseIdStr = String(course.id);
        console.log('获取课程学生，courseId:', courseIdStr);
        
        const response = await axios.get(`/api/admin/courses/${courseIdStr}/students`)
        courseStudents.value = response.data || []
        console.log('获取到学生数量:', courseStudents.value.length)
      } catch (error) {
        console.error('获取课程学生失败:', error)
        ElMessage.error('获取课程学生失败')
      } finally {
        studentsLoading.value = false
      }
    }
    
    let timer = null
    onMounted(() => {
      fetchCourses()
      fetchDepartments()
      // 只定时调用 fetchCourses
      timer = setInterval(() => {
        fetchCourses()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })
    
    return {
      courses,
      loading,
      saving,
      courseDialogVisible,
      studentsDialogVisible,
      courseForm,
      isEditMode,
      searchQuery,
      semesterFilter,
      departmentFilter,
      majorFilter,
      filteredCourses,
      selectedCourse,
      courseStudents,
      studentsLoading,
      currentCourse,
      courseRules,
      openCourseDialog,
      saveCourse,
      deleteCourse,
      viewStudents,
      handleSearch,
      departments,
      majors,
      courseMajors,
      handleDepartmentChange,
      handleCourseDepChange,
      timeSlots,
      scheduleMatrix,
      updateScheduleString
    }
  }
}
</script>

<style scoped>
.admin-course-management {
  margin: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  margin-bottom: 20px;
}

.course-info-header {
  margin-bottom: 20px;
}

.course-info-header h3 {
  margin-bottom: 5px;
}

.failed-grade {
  color: #f56c6c;
}

.schedule-table table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 10px;
}

.schedule-table th, .schedule-table td {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: center;
}

.schedule-table th {
  background-color: #f5f7fa;
}

.schedule-preview {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.description {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}
</style> 